// pages/order_commit_info/order_commit_info.js
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    transfer_other: '',
    transfer_length: '',
    receive_other: '',
    receive_length: '',
    pay_status: false,
    openId: null,
    vip_status: null
  },
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading()
    this.onLoad()
    setTimeout(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    }, 2000);
  },
  pay_order(openId, formId){
    var that = this
    that.setData({
      pay_status: true
    })
    var other = util.getUserdata('other')

    console.log(other);
    var brand_info = util.getUserdata('brand_info')
    console.log(brand_info)
    var transfer_info = util.getUserdata('transfer_info')
    console.log(transfer_info)
    var receive_info = util.getUserdata('receive_info')
    console.log(receive_info)
    wx.showLoading({
      title: '订单提交中',
      icon: 'loading',
      mask: true
    })
    util.request('V2/commitOrder',
      {
        'other': JSON.stringify(other), 
        'brand_info': JSON.stringify(brand_info),
        'transfer_info': JSON.stringify(transfer_info),
        'receive_info': JSON.stringify(receive_info),
        'wx_tmpl_formid': formId,
        'wx_openid': openId,
      },
      function(res){
        var rtn = res
        if(rtn.data.code == 0){
          console.log('wx.requestPayment')
          wx.requestPayment({
            timeStamp: rtn.data.timeStamp,
            nonceStr: rtn.data.nonceStr,
            package: rtn.data.package,
            signType: 'MD5',
            paySign: rtn.data.paySign,
            success(res) {
              that.setData({
                pay_status: false
              })
              console.log('支付成功')
              console.log(res)
              wx.hideLoading()
              //支付成功 清除所有表单数据
              util.setUserdata('transfer_info_apply_nos', "");
              util.clear_all_input()
              util.removeUserData('order_id')
              util.removeUserData('order_number')
              wx.navigateTo({
                url: '../pay_msg/pay_msg?id=' + rtn.data.order_id + '&s=1',
              })
            },
            fail(res) { 
              that.setData({
                pay_status: false
              })
              console.log('支付失败')
              util.setUserdata('transfer_info_apply_nos', "");
              util.clear_all_input()
              util.removeUserData('order_id')
              util.removeUserData('order_number')
              console.log(res)
              wx.navigateTo({
                url: '../pay_msg/pay_msg?id=' + rtn.data.order_id + '&s=0',
              })
            }
          })
        }else if (rtn.data.code == 1){
          console.log(rtn.data)
          that.setData({
            pay_status: false
          })
          wx.showToast({
            title: rtn.data.msg,
            icon: 'none',
            success: function(){
              console.log('余额支付成功')
              util.setUserdata('transfer_info_apply_nos', "");
              util.clear_all_input()
              util.removeUserData('order_id')
              util.removeUserData('order_number')
              setTimeout(() => {
                wx.navigateTo({
                  url: '../pay_msg/pay_msg?id=' + rtn.data.order_id + '&s=1',
                })
              }, 1000);

              
              console.log(res)
              //支付成功 清除所有表单数据
              
            }
          })
          
          
        } else if (rtn.data.code< 0){
          wx.showToast({
            title: rtn.data.msg,
            icon: 'none',
            duration: 2000
          })
          return false
        }else{
          wx.showModal({
            content: rtn.data.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
              }
            }
          })
        }
      }
    )
  },
  upSeal(array,index){
    var that = this
    if(!array[index]) return;
    if(array[index].transfer_type == 2 && array[index].ot == false){
      that.seal_count += 1
        console.log(index)
        console.log(array[index])
        console.log(array[index].seal_path)
        console.log(util.getUserdata('identity_token'))
        console.log(array[index].seal_path_name)
        
        wx.uploadFile({
          url: util.reqUrl('V2/uploadSeal'),
          header: util.headers(),
          formData: { 'identity_token': util.getUserdata('identity_token')},
          filePath: array[index].seal_path_name||'',
          name: 'seal_' + index,
          success(res) {
            var rtn = JSON.parse(res.data)
            array[index].seal_vc = rtn.verify_code
            that.seal_done += 1
            that.upSeal(array,index+1)
          },
          fail(res) {
            wx.showToast({
              title: '企业公章有误,请重新上传',
              icon: 'none',
              duration: 2000
            })
          }
        })
    }else{
      that.upSeal(array,index+1)
    }
  },
  statement_pay : function(e){
    console.log(e)
    var that = this
    var formId = e.detail.formId;
    var openId = that.data.openId;
    console.log(openId)
    console.log(formId)
    var transfer_info = util.getUserdata('transfer_info')
    that.upSeal(transfer_info,0)
    
    var tr = setInterval(function(){
      if(that.seal_count == that.seal_done){
        that.setData({
          personal_list: transfer_info
        })
        util.setUserdata('transfer_info',transfer_info)
        clearInterval(tr)
        
        // that.send_tmplmsg(openId, formId)
        that.pay_order(openId, formId)
        
      }
    },200)
  },
  send_tmplmsg: function (openId, formId){
    console.log('测试模版消息')
    var _this = this;
    if (!formId || 'the formId is a mock one' === formId) {
      _this.setData({
        logMessage: '[fail]请使用真机调试，否则获取不到formId'
      });
      return;
    }

    // 发送随机模板消息
    wx.request({
      url: 'https://gzadmin.ma.cn/wx.php?openid=' + openId + '&formid=' + formId,
      // url: requestHost + "/template_send",
      data: {
        openId: openId,
        formId: formId
      },
      method: 'POST',
      success: function (res) {
        if (res.data.errcode == 0) {
          _this.setData({
            logMessage: '发送模板消息成功[' + new Date().getTime() + ']'
          });
        } else {
          _this.setData({
            logMessage: '[fail]' + JSON.stringify(res)
          });
        }
      },
      fail: function (err) {
        _this.setData({
          logMessage: '[fail]' + JSON.stringify(err)
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (opt) {
    let that = this;
    util.request('V2/myAllInfo', { 'type': 1 },
      function (res) {
        console.log(res);
        var other = util.getUserdata('other')
        var brand_info = util.getUserdata('brand_info')
        var transfer_info = util.getUserdata('transfer_info')
        var receive_info = util.getUserdata('receive_info')

        console.log(transfer_info);
        var transfer_other = '';
        for (var i = 1; i < transfer_info.length; i++) {
          if (transfer_info[i].transfer_type == 2) {
            transfer_other += transfer_info[i].company_name + '(' + transfer_info[i].company_identity_code + ');'
          }
          if (transfer_info[i].transfer_type == 1) {
            transfer_other += transfer_info[i].personal_name + '(' + transfer_info[i].identity_code + ');'
          }
        }

        console.log(transfer_other)

        var receive_other = '';
        for (var i = 1; i < receive_info.length; i++) {
          if (receive_info[i].transfer_type == 1) {
            receive_other += receive_info[i].personal_name + '(' + receive_info[i].identity_code + ');'
          }
          if (receive_info[i].transfer_type == 2) {
            receive_other += receive_info[i].company_name + '(' + receive_info[i].company_identity_code + ');'
          }
        }

        console.log(receive_info);
        var other_money = 0
        var all_money = 0

        var page_money = ''
        var page_number = 0
        var page_count_money = 0
        var base_money = 350

        //会员优惠价格
        let vip_money = 0
        if (res.data.member.is_vip > 0) {
          vip_money = base_money - 70
          base_money = base_money - 70
        }else{
          vip_money = base_money
        }

        if (other.page_count > 2) {
          page_number = other.page_count - 2
          page_money = '20*' + page_number
        } else {
          page_money = '0'
        }

        page_count_money = page_number * 20

        var page_count = other.page_count || 0
        if (other.mail_type) other_money += 100;
        if (other.send_type) other_money += 50;
        if (other.care_type) other_money += 50;
        all_money = base_money + other_money + page_count_money

        

        that.setData({
          openId: res.data.member.openid,
          vip_status: res.data.member.is_vip,
          other: other,
          other_money: other_money,
          page_money: page_money,
          all_money: all_money,
          vip_money: vip_money,
          brand_info: brand_info,
          transfer: transfer_info[0] || {},
          receive: receive_info[0] || {},
          cur_date: util.curDate(),
          transfer_other: transfer_other,
          transfer_length: transfer_info.length,
          receive_info: receive_info,
          receive_length: receive_info.length
        })
      }
    )

    

    // //会员优惠价格
    // let vip_money = 0
    // console.log(data.datas)
    // vip_money = datas.data.member.is_vip > 0 ? all_money - 70 : all_money

    // this.setData({
      
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  seal_count:0,
  seal_done:0
})